import { sm3 } from 'sm-crypto';

/**
 * Transform record to option
 *
 * @example
 *   ```ts
 *   const record = {
 *     key1: 'label1',
 *     key2: 'label2'
 *   };
 *   const options = transformRecordToOption(record);
 *   // [
 *   //   { value: 'key1', label: 'label1' },
 *   //   { value: 'key2', label: 'label2' }
 *   // ]
 *   ```;
 *
 * @param record
 */
export function transformRecordToOption<T extends Record<string, string>>(record: T) {
  return Object.entries(record).map(([value, label]) => ({
    value,
    label
  })) as CommonType.Option<keyof T>[];
}

type MapKeyType = Map<any, any> extends Map<infer K, any> ? K : never;
export function transformMapRecordToOption<T extends Map<any, any>>(record: T) {
  return [...record].map(([value, label]) => ({
    value,
    label
  })) as CommonType.Option<MapKeyType>[];
}

/**
 * Translate options
 *
 * @param options
 */
export function translateOptions(options: CommonType.Option<string | number>[]) {
  return options.map(option => ({
    ...option,
    label: option.label
  }));
}

/**
 * Toggle html class
 *
 * @param className
 */
export function toggleHtmlClass(className: string) {
  function add() {
    document.documentElement.classList.add(className);
  }

  function remove() {
    document.documentElement.classList.remove(className);
  }

  return {
    add,
    remove
  };
}

/** sm3 加密数据 */
export function getSM3HashData(data: string) {
  return sm3(data);
}

/**
 * 通过 value 获取对象 key
 *
 * @param object 目标对象
 * @param value 目标 value
 * @returns 目标 key
 */
export function getKeyByValue<O extends Record<string, string>>(object: O, value: string) {
  return Object.keys(object).find(key => object[key] === value);
}

/** 转换字符串 true 为 布尔值 true，其他为布尔值 false */
export function parseBoolean(value?: any) {
  return value === 'true';
}
